import React, { useEffect, useState } from 'react';
import { Select, Input, Form, message, Tooltip } from 'antd';
import CommonModal from '@/components/CommonModal';
import { mobile, passWord } from '@/utils/rule';
import { isEmpty } from 'lodash';
import { addAccount, updateAccount, checkMobileRepeatOp } from '../service';

const { Option } = Select;
const layout1 = { //发布表单排布
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 17,
  }
};

export default ({ handleOk, handleCancel, roleList, item = {} }) => {

  const [form] = Form.useForm();

  const [isError, setIsError] = useState(false);

  const [open, setOpen] = useState(false);

  const [isOk, setIsOk] = useState(false);

  useEffect(() => {
    setOpen(true);
  }, [])

  //检验手机号是否重复
  const checkMobileIsRepeat = (phone) => {
    return new Promise(async (resolve, reject) => {
      START_LOADING();
      const { data, success } = await checkMobileRepeatOp({ phone, userId: item.id });
      END_LOADING();
      if (success) {
        if (data) {
          resolve();
        } else {
          reject();
          setIsError(true);
        }
      } else {
        reject();
      }
    })
  }

  //表单校验
  const onOk = () => {
    form.validateFields().then(val => {
      checkMobileIsRepeat(val.mobile).then(() => {
        handleSubmit(val);
      })
    })
  }

  //提交
  const handleSubmit = async (val) => {
    const arr = []
    roleList.forEach(item => {
      val.roleIds.forEach(items => {
        if (items == item.label || items == item.value) {
          arr.push(item.value)
        }
      })
    })

    if (arr.length == 0) {
      message.info('原有角色已失效！,请重新选择角色');
      return;
    }

    const params = {
      ...val,
      account: val.account.replace(/\ /g, ''),
      roleIds: arr.join(','),
      id: item.id
    }
    START_LOADING();
    let res;
    if (item.id) {
      res = await updateAccount(params);
    } else {
      res = await addAccount(params);
    }
    END_LOADING()
    if (res.success) {
      if (item.id) {
        message.success('编辑成功！');
      } else {
        message.success('添加成功！');
      }
      setIsOk(true);
      setOpen(false);
    }
  }

  const onCancel = () => {
    setOpen(false);
  }

  //关闭弹框
  const afterClose = () => {
    if(isOk) {
      handleOk();
    } else {
      handleCancel();
    }
  }

  /*限制中英文皆可输入的文本框长度，使用方式参考以下:*/
  const checkLength = (_, value) => {
    let temp = 0;
    for (let i = 0; i < value.length; i++) {
      if (/[\u4e00-\u9fa5]/.test(value[i])) {
        temp += 2;
      } else {
        temp++;
      }
    }
    if (temp <= 20) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('10个汉字或者20个数字子母'));
  };

  return (
    <CommonModal
      title={item.id ? '编辑员工' : '添加员工'}
      open={open}
      width={458}
      onOk={onOk}
      onCancel={onCancel}
      afterClose={afterClose}
    >
      <Form
        {...layout1}
        form={form}
        initialValues={
          item.id ? {
            ...item,
            roleIds: (!isEmpty(item) && item.roleIds) ? item.roleIds.split(',') : []
          } : undefined
        }
      >
        <Form.Item
          name="account"
          label="员工账号"
          validateFirst={true}
          rules={[
            {
              required: true,
              //   max: 20
            },
            // {
            //   pattern: /[A-Za-z0-9]/g,
            //   message: '仅输入大小写字母、数字'
            // },
            {
              validator: checkLength,
            },
            // {
            //   pattern: /^[^\s]*$/,
            //   message: '不能包含空格',
            // }
          ]}>
          <Input placeholder='请输入员工账号' disabled={item.id ? true : false} />
        </Form.Item>
        <Form.Item name="name" label="员工姓名" rules={[{ required: true }]}>
          <Input placeholder='请输入员工姓名' />
        </Form.Item>
        <Form.Item name="mobile" label="联系方式" rules={[
          {
            required: true,
            whitespace: false,
            message: '请输入正确的手机号!',
          },
          mobile
        ]}
          extra={isError && <div className='common-color9'>该手机号已存在</div>}
        >
          <Input placeholder='请输入联系方式' onChange={() => isError && setIsError(false)} />
        </Form.Item>
        <Form.Item
          name="password"
          label="登录密码"
          validateFirst={true}
          rules={[
            passWord
            // {
            //   pattern: /[A-Za-z0-9^#!@%&'.,;=?$]/g,
            //   message: '仅输入字母、数字、特殊字符,不包含空格和中文'
            // },
            // {
            //   pattern: /^[^\s\u4e00-\u9fa5]*$/,
            //   message: '仅输入字母、数字、特殊字符,不包含空格和中文'
            // }
          ]}
        >
          <Input.Password placeholder='请输入登录密码' autoComplete="new-password" />
        </Form.Item>
        <Form.Item name="roleIds" label="角色" rules={[{ required: true, message: '请选择角色' }]} >
          <Select
            mode="multiple"
            placeholder='请输入'
            optionFilterProp='children'
            options={roleList}
          />
        </Form.Item>
      </Form>
    </CommonModal>
  )
}